# -*- coding: utf-8 -*-
import pandas as pd
import mplfinance as mpf
import matplotlib.pyplot as plt
from binance.client import Client
from datetime import datetime, timedelta

from tdx import Zhibiao

# 1. 设置全局中文字体
style = mpf.make_mpf_style(
    base_mpf_style='charles',
    rc={'font.family': 'SimHei', 'axes.unicode_minus': False}
)


# 2. 获取Binance数据
def get_binance_data(symbol='BTCUSDT', interval='1h', days=180):
    proxies = {
        'http': 'socks5://127.0.0.1:10010',
        'https': 'socks5://127.0.0.1:10010',
    }
    # 初始化Binance客户端 (不需要API密钥获取K线数据)
    client = Client(requests_params={'proxies': proxies, 'timeout': 10})
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days)

    # klines = client.get_historical_klines(
    #     symbol=symbol,
    #     interval=interval,
    #     start_str=start_date.strftime('%Y-%m-%d'),
    #     end_str=end_date.strftime('%Y-%m-%d')
    # )

    klines = client.futures_klines(symbol="BTCUSDT", interval="5m", limit=200)

    df = pd.DataFrame(klines, columns=[
        'Open time', 'open', 'high', 'low', 'close', 'volume',
        'Close time', 'Quote asset volume', 'Number of trades',
        'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore'
    ])

    df['Open time'] = pd.to_datetime(df['Open time'], unit='ms')
    df.set_index('Open time', inplace=True)
    return df[['open', 'high', 'low', 'close', 'volume']].astype(float)


# 3. 获取数据
data = get_binance_data(symbol='BTCUSDT', interval='1d', days=90)
df = data
fxxs,buy = Zhibiao.ths_chaodi(df)
print(fxxs)
# 创建副图对象
apds = [
    mpf.make_addplot(
        fxxs,
        panel=2,  # 在第1个副图绘制
        color="red",
        ylabel="RSI (14)",
        linestyle="-",
        alpha=0.8
    ),
    mpf.make_addplot([80] * len(fxxs), panel=2, color="red", linestyle="-"),  # 超买线
    mpf.make_addplot([20] * len(fxxs), panel=2, color="green", linestyle="-")  # 超卖线
    # mpf.make_addplot([50] * len(fxxs), panel=2, color="blue", linestyle="-")

]

# 4. 创建图表
fig, axes = mpf.plot(
    data,
    addplot=apds,
    type='candle',
    title='BTC/USDT 日K线',
    ylabel='价格（美元）',
    volume=True,
    style=style,
    returnfig=True
)


# 5. 交互功能类
class CandleHover:
    def __init__(self):
        self.annotation = None
        self.vline = None

    def __call__(self, event):
        # 鼠标移出图表区域时清除所有标记
        if not event.inaxes or event.xdata is None:
            self._cleanup()
            return

        try:
            idx = int(round(event.xdata))
            if 0 <= idx < len(data):
                candle = data.iloc[idx]
                self._update_annotations(idx, candle, event)
            else:
                self._cleanup()
        except:
            self._cleanup()

        fig.canvas.draw_idle()

    def _update_annotations(self, idx, candle, event):
        # 计算涨跌幅
        change = (candle['close'] - candle['open']) / candle['open'] * 100

        # 移除旧元素
        self._cleanup()

        # 添加竖线
        self.vline = axes[0].axvline(x=idx, color='dodgerblue', alpha=0.7, linestyle='--')

        # 添加注释框
        text = (f"日期: {data.index[idx].strftime('%Y-%m-%d')}\n"
                f"开盘: {candle['open']:.2f}\n"
                f"收盘: {candle['close']:.2f}\n"
                f"指标: {fxxs[idx]:.2f}\n"
                f"涨跌幅: {change:+.2f}%")

        self.annotation = axes[0].annotate(
            text,
            xy=(idx, candle['high']),
            xytext=(10, 10),
            textcoords='offset points',
            bbox=dict(boxstyle='round', fc='w', ec='0.5', alpha=0.9),
            arrowprops=dict(arrowstyle='->', connectionstyle='arc3')
        )

    def _cleanup(self):
        """清除所有交互元素"""
        if self.annotation:
            self.annotation.remove()
            self.annotation = None
        if self.vline:
            self.vline.remove()
            self.vline = None


# 绑定事件
hover = CandleHover()
fig.canvas.mpl_connect('motion_notify_event', hover)

plt.tight_layout()
plt.show()